<template>
  <div class="head-container">
    <el-input v-model="courseName" class="mb-20px" clearable placeholder="请输入课程名称">
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
  </div>
  <div class="head-container">
    <el-tree
      ref="treeRef"
      :data="courseList"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :props="defaultProps"
      default-expand-all
      highlight-current
      node-key="id"
      @node-click="handleNodeClick"
    />
  </div>
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
import { CourseApi } from '@/api/school/course'
import { defaultProps, handleTree } from '@/utils/tree'
import {useRoute } from 'vue-router'
const route = useRoute()

// defineOptions({ name: 'SystemUserDeptTree' })

const courseName = ref('')
const courseList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()

const queryParams = {
  visibility: ''
}

/** 获得课程树 */
const getTree = async () => {
  const res = await CourseApi.getSimpleCourseList(queryParams)
  courseList.value = []
  courseList.value.push(...handleTree(res))
}

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

/** 处理课程被点击 */
const handleNodeClick = async (row: { [key: string]: any }) => {
  emits('node-click', row)
}
const emits = defineEmits(['node-click'])

/** 监听courseName */
watch(courseName, (val) => {
  treeRef.value!.filter(val)
})

// 路由到 categoryId 映射关系
const pathTovisibilityMap = {
  '/course/garden/course-unit': '0',  //园所课程
  '/course/my-course/mycourseunit': '1',   //我的课程
  // 可以继续扩展更多路径
}

/** 监听路由，判断是从哪个菜单请求的，然后赋值不同的类型 */
watch(() => route.path, (path) => {
  console.log(path, '---path');
  
  // 匹配路径并赋值 resourceCode 
  queryParams.visibility = pathTovisibilityMap[path] || 1  
  console.log(queryParams.visibility, '---visibility');
  
}, {
  immediate: true  //立即执行一次
})

/** 初始化 */
onMounted(async () => {

  await getTree()
})
</script>
